#region License
/* ---------------------------------------------------------------- *
 *
 * This file is part of the Xcoordination Application Space
 * ("XcoAppSpace") http://www.xcoordination.com
 *
 * Copyright (C) 2009 Xcoordination http://www.xcoordination.com
 *
 * XcoAppSpace is free software; you can redistribute it and/or
 * modify it under the terms of version 2 of the GNU General
 * Public License as published by the Free Software Foundation.
 *
 * XcoAppSpace is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses/
 * or write to the Free Software Foundation, Inc., 51 Franklin
 * Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * ---------------------------------------------------------------- */
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using TypeResolve;

namespace XcoAppSpaces.Serialization.Binary
{
	/// <summary>
	/// Surrogate that serializes types only by their name, therefore allowing interoperability 
	/// between different versions of signed assemblies.
	/// </summary>
	class TypeSerializationSurrogate : ISerializationSurrogate
	{
		private readonly Dictionary<string, Type> typeMappings = new Dictionary<string, Type>();

		public void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
		{
			info.AddValue("typeName", ((Type) obj).FullName);
		}

		public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
		{
			var name = info.GetString("typeName");
			Type type;
			lock (typeMappings) //lock needed?
			{
				if (!typeMappings.TryGetValue(name, out type))
				{
					type = TypeUtils.SearchType(name);
					if (type == null)
					{
						//in case the type cannot be found try converting it into a short typename (all assembly infos removed) and then use the more sophisticated
						//TypeResolver which resolves every generic sub part of the type on its own
						var shortTypeName = TypeNameConverter.ToShortTypeName(name);
						//Console.WriteLine("Type " + name + " not found, trying to resolve short name: " + shortTypeName);
						type = TypeResolver.Resolve(shortTypeName);
						if (type == null)
							throw new SerializationException(String.Format("Type \"{0}\" could not be found in any loaded assembly.", name));
					}
					typeMappings[name] = type;
				}
			}
			return type;
		}
	}
}
